package com.lyf.core.action;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.lyf.core.pojo.Menu;
import com.lyf.core.pojo.User;
import com.lyf.core.service.MenuService;
import com.lyf.core.service.UserService;
import com.lyf.core.util.CommonUtils;
import com.lyf.core.util.RSACoder;

@Controller
public class Index {
	Logger logger = Logger.getLogger(getClass());
	
	@Autowired
	private HttpSession session;
	   
	@Autowired
	private UserService userService;
	
	@Autowired
	private MenuService menuService;

	@RequestMapping("/index")
	public ModelAndView index() {
		ModelAndView view = new ModelAndView();
		
		Object user  = session.getAttribute("user");
		
		if(user  != null && user instanceof User) {
			 //重新获取user 加入session
	        User u = (User)user;
	        //查询用户的权限菜单
	        List<Menu> ms = menuService.findByUser(u.getUser_id(), false, true);
	        view.addObject("ms", ms);
		}
		
		
		
		return view ;
	}
	
	@RequestMapping("/welcome")
	public String welcome() {
		return null ;
	}
	
	@RequestMapping("/unauthorized")
	public String unauthorized() {
		return null ;
	}
	
	@RequestMapping("/logout")
	public ModelAndView logout() {
		ModelAndView view = new ModelAndView("login");
		
		SecurityUtils.getSubject().logout();
		session.invalidate();
		return view ;
	}
	
	@RequestMapping("/login")
	public ModelAndView login() {
		ModelAndView view = new ModelAndView("login");
		
		//带上令牌等其他数据
		
		return view ;
	}
	
	@RequestMapping("/login_validate")
	public ModelAndView login_validate(User user , String randomCode , Boolean online) { 
		ModelAndView view = new ModelAndView();
		 try{
			 if (!isRelogin(user)){ 
				 // 如果已经登陆，无需重新登录  
				 //从session中取出验证码原文
				 Object kaptcha_key = session.getAttribute("KAPTCHA_SESSION_KEY");
				 if(kaptcha_key == null || randomCode == null || !kaptcha_key.equals(randomCode)) {

					 view.setViewName("login");
					 view.addObject("error" , "验证码错误");
					 return view;
				 }

				 Subject subject = SecurityUtils.getSubject();
				//解密
				 String newpass = RSACoder.decryptByPrivateKey(user.getUser_pass()); 

				 //md5加密
				 String md5_pass = CommonUtils.md5(user.getUser_id(), newpass);

				 UsernamePasswordToken token = new UsernamePasswordToken(user.getUser_id(), md5_pass);

				 subject.login(token);//会跳到我们自定义的realm中
				 
				 if(online != null ) {
					 token.setRememberMe(online);
				 }
			 }
		 
			
            
            //重新获取user 加入session
            user = userService.findByUserId(user.getUser_id());
			user.setUser_pass(null);
            
            session.setAttribute("user", user);
            view.setViewName("redirect:/index");
            
           
            
			return view ;
        }catch(Exception e){
            e.printStackTrace(); 
            logger.error("login error , user_id:" + user.getUser_id() + " , userpass : " + user.getUser_pass() , e);
            view.setViewName("login");
			view.addObject("error" , "账号或密码错误");
			 
			 return view ;
        }
		
		 
	}
	
	private boolean isRelogin(User user) {  
	    Subject us = SecurityUtils.getSubject();  
	        if (us.isAuthenticated()) {  
	           return true; // 参数未改变，无需重新登录，默认为已经登录成功  
	        }  
	        return false; // 需要重新登陆  
	} 
}
